package com.amt.iptvsetting.business.database;

import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.amt.iptvsetting.R;
import com.app.common.CommonManagerKt;
import com.app.common.activity.BaseActivity;
import com.app.common.adapter.BaseRecyclerViewAdapter;
import com.app.datamanagermodule.DataManagerModuleKt;
import com.app.datamanagermodule.dao.UserDao;
import com.app.datamanagermodule.entity.User;

import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.CompletableObserver;
import io.reactivex.SingleObserver;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;


@Route(path = "/zhouwd/database_activity")
public class DataBaseActivity extends BaseActivity {

    private static final String TAG = DataBaseActivity.class.getSimpleName();

    @BindView(R.id.activity_database_list)
    RecyclerView activityDatabaseList;

    private List<User> data = new ArrayList<>();

    private ListAdapter adapter;

    private UserDao userDao;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_database);
        ButterKnife.bind(this);

        initData();

        initAdapter();


    }

    private void initData() {

        userDao = DataManagerModuleKt.getUserDao();

        Log.i(TAG, "initData: userDao -> " + userDao);

        if (userDao == null) {
            return;
        }

        userDao.selectAllUsers().subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new SingleObserver<List<User>>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        Log.i(TAG, "onSubscribe: ");
                    }

                    @Override
                    public void onSuccess(List<User> users) {
                        Log.i(TAG, "initData: users -> " + users);
                        data.clear();
                        data.addAll(users);

                        if (adapter != null && data.size() > 0) {

                            adapter.notifyDataSetChanged();
                            activityDatabaseList.smoothScrollToPosition(data.size() - 1);
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        Log.i(TAG, "onError: ");
                    }
                });


    }


    private void initAdapter() {

        adapter = new ListAdapter(data, this);

        activityDatabaseList.setLayoutManager(new LinearLayoutManager(this));

        activityDatabaseList.setAdapter(adapter);
        if (data.size() > 0) {
            activityDatabaseList.smoothScrollToPosition(data.size() - 1);
        }
    }



    @OnClick(R.id.activity_database_add)
    public void onActivityDatabaseAddClicked() {
        User user = new User();
        user.setUserName("zhouwd" + System.currentTimeMillis());
        user.setPhoneNum("1321964");
        user.setAge(23);
        userDao.insertUsers(user).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new SingleObserver<Long>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        Log.i(TAG, "onSubscribe: ");
                    }

                    @Override
                    public void onSuccess(Long aLong) {
                        Log.i(TAG, "onSuccess: aLong -> " + aLong);
                        user.setId(aLong);
                        data.add(user);
                        adapter.notifyItemRangeInserted(data.size() - 1, 1);
                        if (data.size() > 0) {
                            activityDatabaseList.smoothScrollToPosition(data.size() - 1);
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        Log.i(TAG, "onError: ");
                    }
                });

    }

    @OnClick(R.id.activity_database_delete)
    public void onActivityDatabaseDeleteClicked() {

        if (data.size() <= 0) {
            return;
        }
        User user = data.get(data.size() - 1);
        userDao.deleteUsers(user)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new CompletableObserver() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        Log.i(TAG, "onSubscribe: ");
                    }

                    @Override
                    public void onComplete() {
                        data.remove(user);
                        if (adapter != null) {
                            adapter.notifyItemRangeRemoved(data.size(), 1);
                        }

                        CommonManagerKt.showShortToast("删除成功");
                        if (data.size() > 0) {
                            activityDatabaseList.smoothScrollToPosition(data.size() - 1);
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        CommonManagerKt.showShortToast("删除失败");
                    }
                });
    }

    @OnClick(R.id.activity_database_update)
    public void onActivityDatabaseUpdateClicked() {

    }

    @OnClick(R.id.activity_database_query)
    public void onActivityDatabaseQueryClicked() {

    }

    @OnClick(R.id.activity_database_clear)
    public void onActivityDatabaseClearClicked() {
        userDao.deleteAllUsers(data)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new CompletableObserver() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        Log.i(TAG, "onSubscribe: ");
                    }

                    @Override
                    public void onComplete() {
                        CommonManagerKt.showShortToast("清空完成");
                        data.clear();
                        if (adapter != null) {
                            adapter.notifyDataSetChanged();
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        CommonManagerKt.showShortToast("清空失败");
                    }
                });
    }

    class ListAdapter extends BaseRecyclerViewAdapter<User, ListAdapter.ViewHolder> {

        public ListAdapter(@NotNull List<? extends User> data, @NotNull Context context) {
            super(data, context);

        }

        @NonNull
        @Override
        public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            View view = getInflater().inflate(R.layout.activity_database_item, parent, false);
            return new ViewHolder(view);
        }

        @Override
        public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
            try {
                User user = getData().get(position);

                holder.activityDatabaseItemId.setText(String.valueOf(user.getId()));

                holder.activityDatabaseItemAge.setText(String.valueOf(user.getAge()));

                holder.activityDatabaseItemName.setText(user.getUserName());

                holder.activityDatabaseItemPhoneNum.setText(user.getPhoneNum());

            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        class ViewHolder extends RecyclerView.ViewHolder {
            @BindView(R.id.activity_database_item_id)
            TextView activityDatabaseItemId;
            @BindView(R.id.activity_database_item_name)
            TextView activityDatabaseItemName;
            @BindView(R.id.activity_database_item_age)
            TextView activityDatabaseItemAge;
            @BindView(R.id.activity_database_item_phone_num)
            TextView activityDatabaseItemPhoneNum;
            public ViewHolder(@NonNull View itemView) {
                super(itemView);
                ButterKnife.bind(this, itemView);
            }
        }

    }

}
